package com.allqj.sfx.ddd.member.infrastructure.repository;

import com.allqj.sfx.ddd.member.domain.entity.flow.FlowInstance;
import com.allqj.sfx.ddd.member.domain.repository.FlowInstanceRepository;
import com.allqj.sfx.ddd.member.infrastructure.dao.FlowInstanceDAO;
import com.allqj.sfx.ddd.member.infrastructure.po.FlowInstanceDO;
import com.allqj.sfx.ddd.member.infrastructure.converter.FlowInstanceConverter;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * @author sjw
 * @className FlowInstanceTaskRepositoryImpl
 * @date 2022/7/22 11:22
 * @description: FlowInstanceRepository具体实现
 * Repository接口定义位于domain层
 * Repository接口具体实现位于infrastructure层
 * 与底层db解耦
 */
@Repository
public class FlowInstanceRepositoryImpl implements FlowInstanceRepository {

    private final FlowInstanceDAO dao;

    public FlowInstanceRepositoryImpl(FlowInstanceDAO dao) {
        this.dao = dao;
    }


    @Override
    public FlowInstance flowInstance(Integer id) {
        Optional<FlowInstanceDO> flowInstanceDO = dao.findById(id);
        return flowInstanceDO.map(instanceDO -> FlowInstanceConverter.INSTANCE.do2Entity(instanceDO)).orElse(null);
    }

    @Override
    public FlowInstance save(FlowInstance flowInstance) {
        if (flowInstance == null) return null;
        FlowInstanceDO flowInstanceDO = FlowInstanceConverter.INSTANCE.entity2Do(flowInstance);
        flowInstanceDO = dao.save(flowInstanceDO);
        return FlowInstanceConverter.INSTANCE.do2Entity(flowInstanceDO);
    }
}
